import React, { Component } from 'react';
import '../styles/Login.css'
import {user_login,user_register} from '../api/index'
class Login extends Component {
    constructor(props){
        super(props);
        this.state = {phone:'',pass:'',agree:false }
    }
    handleChange(e){
        this.setState({
            [e.target.name] : e.target.type == 'checkbox' ? e.target.checked : e.target.value
        })
    }
    register(){
        user_register({phone:'',pass:''}).then((res)=>{
            console.log(res);
        })
    }
    login(){
        console.log(this.state);
        if (this.state.phone.trim()!='' && this.state.pass.trim()!='') {
            if (this.state.agree) {
                //发登录请求
                if (this.state.phone == localStorage.getItem("phone") && this.state.pass == localStorage.getItem("pass")) {
                    user_login({phone: localStorage.getItem("phone"),pass: localStorage.getItem("pass")}).then((res)=>{
                        console.log(res.data.token);
                        alert('登录成功')
                        localStorage.setItem('token',res.data.token)
                        this.props.history.push('/home')
                    })
                } else {
                    alert('核实手机号或密码是否正确')
                }
            }else{
                alert('请先勾选用户登录协议!')
            }
        } else {
            alert('请输入内容')
        }
        
    }
    
    render() {
        return (
            <div className='login'>
                <div className="title">登录页</div>
                <div className="block">
                    {/* 对于input textarea select通过value属性和onChange事件让原本非受控的表单元素变为受控元素 */}
                    <input name='phone' value={this.state.phone} onChange={(e)=>{this.handleChange(e)}} type="text" placeholder='输入手机号' />
                </div>
                <div className="block">
                    <input name='pass'  value={this.state.pass} onChange={(e)=>{this.handleChange(e)}} type="text" placeholder='输入密码' />
                </div>
                <div className="block check">
                    {/* 对于单选,复选 通过checked属性和onChange事件让原本非受控的表单元素变为受控元素 */}
                    <input name='agree'  checked={this.state.agree} onChange={(e)=>{this.handleChange(e)}} type="checkbox"  />勾选用户登录协议
                </div>
                <div className="block ">
                    <input type="button" value='登录'  onClick={()=>{this.login()}}/>
                </div>
                <span onClick={()=>{this.props.history.push('/register')}}>去注册</span>
                {/* <a href="#" onClick={()=>{this.register()}}>去注册</a> */}
               {/*  <div className="block ">

                    <input type="button" value='注册'  onClick={()=>{this.register()}}/>
                </div> */}
            </div>
        );
    }
}

export default Login;